/**
 * tableService - factory
 * 封装一个table数据服务
 */
class tableService {
    constructor($rootScope, $state, $cookieStore, ngDialog, iRunner, dialogService, scoreService, runnerService) {

        var vm = this;

        vm.$state        = $state;
        vm.$cookieStore  = $cookieStore;
        vm.ngDialog      = ngDialog;
        vm.iRunner       = iRunner;
        vm.dialogService = dialogService;
        vm.scoreService  = scoreService;
        vm.runnerService = runnerService;

        vm.URL = iRunner.config.baseUrl;

        // 声明对象缓存接口
        vm.OBJ = {
            RunnerListUrl: vm.URL + '/runner/lists?race_id=',
            ChipListUrl: vm.URL + '/chip/lists?race_id=',
            ScoreListUrl: vm.URL + '/score/lists?race_id=',
            RawdataListUrl: vm.URL + '/rawdata/lists?race_id=',
            PersonListUrl: vm.URL + '/realtime/lists?race_id=',
        }

        // 表格数据
        vm.TableFn = (params, element, baseUrl, headers, search, columns, type) => {
        	var self=this;
        	
            //用于保存实时成绩页面
            $rootScope.realtimeData = {
                type:  type,
                list: []
            }; 

            var tableData = angular.element(element).DataTable($.extend({}, vm.iRunner.settings.dataTable, {
                // --- Data
                ajax: baseUrl + search + '&access-token=' + this.$cookieStore.get('access_token'),
                order: [0, "desc"], // ID 倒序
                // --- Column       
                columns: columns,
                // --- CreatedRow
                createdRow: ( row, data, index ) => {
//                    console.log(data)
                    if ( element=='#rawdata_table'&&!data.chip_no ) {
                        $(row).addClass('highlight');
                    }

                    //保存页面实时数据
                    $rootScope.realtimeData.list.push(data);

                },
                // --- Callback
                initComplete: () => {
                    console.log('initComplete')
                }
            }));

            self.search=function(){
            	tableData.search($('#search_input').val()).draw();
            };
            
            // 点击按钮搜索
            $('#search_btn').on('click', () => {
            	self.search();
            });

            // 按下回车搜索
            $('#search_input').on({
                "keydown": function(evt) {
                    if (evt.which === 13) {
                    	self.search();
                    }
                }
            });

            // 下拉框过滤
            $('.dataTables_length').find('select').on('change', function(event) {
                const select =  $('.dataTables_length').find('select')
                select.val($(this).val())
            });
            
            //点击置无效按钮
            $(element).on('click', "tbody > tr [data-action='realtime_list']", function() {
                vm.ngDialog.open({
                    template: "<p>确定要将" + $(this).data('bib') +"选手置无效吗？<br> 点击确定按钮后，该选手所有成绩无效，实时成绩列表中不在显示该选手！</p><br><button class='btn btn-primary' ng-click='setDNF(" + $(this).data('scoreid') + ")'>确定</button>",
                    className: 'ngdialog-theme-default ngdialog-alert',
                    plain: true,
                    scope: $rootScope
                });

            });

            // 改变领取赛包状态
            $(element).on('click', "tbody > tr [data-action='claimpack']", function() {
                // TODO

                vm.ngDialog.open({
                    template: "<p>确定要将" + $(this).data('bib') +"选手赛包设置为已领取吗？<br> 点击确定按钮后，该选手赛包状态将设为已领取！</p><br><button class='btn btn-primary' ng-click='setClaimpack(" + $(this).data('runnerid') + ")'>确定</button>",
                    className: 'ngdialog-theme-default ngdialog-alert',
                    plain: true,
                    scope: $rootScope
                });

            });

            //设置选手赛包状态
            $rootScope.setClaimpack = function(value) {

                //调用接口，置选手无效
                vm.runnerService.postRunnerClaimpack(headers, value)
                .then( data => {
                    // 成功调用
                    data.code==0&&vm.dialogService.success('调用成功');
                    // 调用失败, 提示用户
                    data.code!=0&&vm.dialogService.error(data.message);
                    console.log(data)
                }, error => console.log('error'));                    

                //关闭确认充值模态框
                vm.ngDialog.close();
                // 重新载入页面
                vm.$state.reload();
            };

            //置选手无效按钮点击确认
            $rootScope.setDNF = function(value) {

                //调用接口，置选手无效
                vm.scoreService.getRealtimeupdateScore(headers, value + '&op=disabled')
                .then( data => {
                    // 成功调用
                    data.code==0&&vm.dialogService.success('调用成功');
                    // 调用失败, 提示用户
                    data.code!=0&&vm.dialogService.error(data.message);
                    console.log(data)
                }, error => console.log('error'));                    

                //关闭确认充值模态框
                vm.ngDialog.close();
                // 重新载入页面
                vm.$state.reload();
            };


            // 点击编辑
            $(element).on('click', 'tbody > tr a', function() {

                if (!params) return;

                console.log(params);

                var data = {},
                    that = $(this),
                    link = $(this);

                if (!link.data('id')) return;

                if (link.data('course')) {
                    data['course_id'] = link.data('course')
                }    

                if (link.data('id')) {    
                    data[params.id] = link.data('id');
                    vm.$state.go(params.name, data);
                }
            });

            // 原始数据详情表格配置
            function rawdata_table(obj) {

                let data = obj;

                for(var i in data){
                    if (data.hasOwnProperty(i)) {
                        data[i] = data[i] && data[i] != 0 ? data[i] : '-'
                    }
                }
                
                return `<table class="table-detail">
                    <tr>
                        <td>芯片Mac:</td>
                        <td>${data.chip_mac}</td>
                    </tr>
                </table>`;
            }

            // 参赛选手详情表格配置
            function runner_table(obj) {

                let data = obj;

                for(var i in data){
                    if (data.hasOwnProperty(i)) {
                        data[i] = data[i] && data[i] != 0 ? data[i] : '-'
                    }
                }

                return `<table class="table-detail">
                    <tr>
                        <td>国籍:</td>
                        <td>${data.nationality}</td>
                    </tr>
                    <tr>
                        <td>城市:</td>
                        <td>${data.city}</td>
                    </tr>
                    <tr>
                    <tr>
                        <td>地址:</td>
                        <td>${data.address}</td>
                    </tr>
                    <tr>
                        <td>年龄:</td>
                        <td>${data.age}</td>
                    </tr>
                    <tr>
                        <td>血型:</td>
                        <td>${data.blood_type}</td>
                    </tr>
                    <tr>
                        <td>邮箱:</td>
                        <td>${data.runner_email}</td>
                    </tr>
                        <td>手机号码:</td>
                        <td>${data.runner_cell}</td>
                    </tr>
                    <tr>
                        <td>身份证:</td>
                        <td>${data.identity}</td>
                    </tr>
                </table>`
            }

            // 详情表格配置
            let format = [
                {
                    id: '#rawdata_table',
                    fn: rawdata_table
                },
                {
                    id: '#runner_table',
                    fn: runner_table
                }

            ]

            // 点击显示详情表格
            $(element + ' tbody').on('click', 'td.details-control', function (event) {
                event.stopPropagation();
                var tr = $(this).closest('tr');
                var row = tableData.row( tr );
         
                if ( row.child.isShown() ) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    // Open this row
                    angular.forEach(format, (value, index) => {
                        if (value.id == element) {
                            row.child( value.fn(row.data()) ).show();
                        }
                    })
                    
                    tr.addClass('shown');
                }
            });
            
            return self;
        }

    }

    // 选手信息
    getRunnerData(params, headers, search) {
        return this.TableFn(params, '#runner_table', this.OBJ.RunnerListUrl, headers, search, iRunner.commonColumns);
    }

    // 计时芯片信息
    getChipData(params, headers, search) {
        return this.TableFn(params, '#chip_table', this.OBJ.ChipListUrl, headers, search, iRunner.chipColumns);
    }

    // 成绩信息
    getScoreData(params, headers, search) {
        return this.TableFn(params, '#score_table', this.OBJ.ScoreListUrl, headers, search, iRunner.scoreColumns);
    }

    // 原始数据
    getRawData(params, headers, search) {
        return this.TableFn(params, '#rawdata_table', this.OBJ.RawdataListUrl, headers, search, iRunner.rawdataColumns);
    }

    // 个人实时成绩--单程
    getPersonOnewayList(params, headers, search) {
        return this.TableFn(params, '#person_table', this.OBJ.PersonListUrl, headers, search, iRunner.onewayColumns, 'oneway');
    }

    // 个人实时成绩--绕圈
    getPersonCircleList(params, headers, search) {
        return this.TableFn(params, '#person_table', this.OBJ.PersonListUrl, headers, search, iRunner.circleColumns, 'circle');
    }

}

tableService.$inject = ['$rootScope', '$state', '$cookieStore', 'ngDialog', 'iRunner', 'dialogService', 'scoreService', 'runnerService'];

export default tableService;